package wlt.plan.controller;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.TextField;
import wlt.plan.model.TodoItem;

public class Search {
    private final TextField searchField;
    private ObservableList<TodoItem> originalItems;
    private final ObservableList<TodoItem> filteredItems;
    
    public Search() {
        this.searchField = new TextField();     // 内部创建 TextField，不依赖外部传入
        this.searchField.setPromptText("搜索待办事项...");
        this.filteredItems = FXCollections.observableArrayList();
        
        // 文本变化监听器
        this.searchField.textProperty().addListener((observable, oldValue, newValue) -> {
            filterTasks(newValue);
        });
    }
    
    public void setOriginalItems(ObservableList<TodoItem> items) {
        this.originalItems = items;
        filterTasks("");
    }
    
    private void filterTasks(String keyword) {
        if (originalItems == null) {
            return;
        }
        
        filteredItems.clear();
        
        if (keyword == null || keyword.trim().isEmpty()) {
            filteredItems.addAll(originalItems);
            return;
        }
        
        String lowerKeyword = keyword.toLowerCase();
        for (TodoItem item : originalItems) {
            if (item.getText().toLowerCase().contains(lowerKeyword)) {
                filteredItems.add(item);
            }
        }
    }
    
    public ObservableList<TodoItem> getFilteredItems() {
        return filteredItems;
    }
    
    public TextField getSearchField() {
        return searchField;
    }
}